﻿//-----------------------------------------------------------------------
// <copyright file="QueueBuild.cs">(c) http://TfsBuildExtensions.codeplex.com/. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace TfsBuildExtensions.Activities.TeamFoundationServer
{
    using System;
    using System.Activities;
    using System.ComponentModel;
    using System.Globalization;
    using System.Text.RegularExpressions;
    using Microsoft.TeamFoundation.Build.Client;
    using System.Linq;
    using System.Web;
    using Microsoft.TeamFoundation.Build.Workflow;
using Microsoft.TeamFoundation.Build.Workflow.Activities;
using System.Collections.Generic;

    /// <summary>
    /// Workflow activity that queues a new build with the specified build definition
    /// and TFS Build Server.
    /// </summary>
    [BuildActivity(HostEnvironmentOption.All)]
    public sealed class QueueBuild : BaseCodeActivity
    {
        /// <summary>
        /// The build to queue
        /// </summary>
        [Browsable(true)]
        public InArgument<string> BuildDefinitionName { get; set; }

        /// <summary>
        /// Queue the build specified in BuildDefinitionName
        /// </summary>
        protected override void InternalExecute()
        {
            this.LogBuildMessage(string.Format(CultureInfo.CurrentCulture, "InternalExecute enter."), BuildMessageImportance.Low);
            var buildDetail = this.ActivityContext.GetExtension<IBuildDetail>();
            if (buildDetail == null) throw new InvalidOperationException("buildDetail");
            var buildDefinitionName = this.BuildDefinitionName.Get(this.ActivityContext);
            if (string.IsNullOrWhiteSpace(buildDefinitionName))
            {
                this.LogBuildWarning(string.Format(CultureInfo.CurrentCulture, "BuildDefinitionName is empty. A build will not be queued."));
                return;
            }

            var buildDefinition = buildDetail.BuildServer.GetBuildDefinition(buildDetail.TeamProject, buildDefinitionName);
            var buildRequest = buildDetail.BuildServer.CreateBuildRequest(buildDefinition.Uri);

            var dictionary = new Dictionary<string,object>();
            dictionary.Add("BuildUri", buildDetail.Uri.ToString());
            buildRequest.ProcessParameters = WorkflowHelpers.SerializeProcessParameters(dictionary);
            buildDetail.BuildServer.QueueBuild(buildRequest);
        }
    }
}
